package com.vibrationkeyboard.app.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.google.gson.Gson
import com.vibrationkeyboard.app.model.SensorData
import kotlinx.coroutines.*
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.*

class DataSyncService : Service() {

    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    private val gson = Gson()
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault())
    
    companion object {
        private const val TAG = "DataSyncService"
        private const val DATA_DIR = "vibration_keyboard_data"
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "DataSyncService created")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "DataSyncService started")
        
        when (intent?.action) {
            "SYNC_SENSOR_DATA" -> {
                val sensorData = intent.getParcelableExtra<SensorData>("sensor_data")
                if (sensorData != null) {
                    syncSensorData(sensorData)
                }
            }
            "EXPORT_DATA" -> {
                exportDataToFile()
            }
            "CLEAR_DATA" -> {
                clearDataFiles()
            }
        }
        
        return START_NOT_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onDestroy() {
        super.onDestroy()
        serviceScope.cancel()
        Log.d(TAG, "DataSyncService destroyed")
    }

    private fun syncSensorData(sensorData: SensorData) {
        serviceScope.launch {
            try {
                val dataDir = File(filesDir, DATA_DIR)
                if (!dataDir.exists()) {
                    dataDir.mkdirs()
                }

                val timestamp = dateFormat.format(Date())
                val fileName = "sensor_data_$timestamp.json"
                val file = File(dataDir, fileName)

                val dataJson = gson.toJson(sensorData)
                FileWriter(file).use { writer ->
                    writer.write(dataJson)
                }

                Log.d(TAG, "Sensor data synced to file: $fileName")
            } catch (e: Exception) {
                Log.e(TAG, "Error syncing sensor data", e)
            }
        }
    }

    private fun exportDataToFile() {
        serviceScope.launch {
            try {
                val dataDir = File(filesDir, DATA_DIR)
                if (!dataDir.exists()) {
                    Log.w(TAG, "No data directory found")
                    return@launch
                }

                val timestamp = dateFormat.format(Date())
                val exportFileName = "export_$timestamp.json"
                val exportFile = File(filesDir, exportFileName)

                val dataFiles = dataDir.listFiles { file ->
                    file.extension == "json"
                } ?: emptyArray()

                val allData = mutableListOf<SensorData>()
                dataFiles.forEach { file ->
                    try {
                        val jsonContent = file.readText()
                        val sensorData = gson.fromJson(jsonContent, SensorData::class.java)
                        allData.add(sensorData)
                    } catch (e: Exception) {
                        Log.e(TAG, "Error reading file: ${file.name}", e)
                    }
                }

                val exportData = mapOf(
                    "timestamp" to timestamp,
                    "total_records" to allData.size,
                    "data" to allData
                )

                val exportJson = gson.toJson(exportData)
                FileWriter(exportFile).use { writer ->
                    writer.write(exportJson)
                }

                Log.d(TAG, "Data exported to: $exportFileName")
            } catch (e: Exception) {
                Log.e(TAG, "Error exporting data", e)
            }
        }
    }

    private fun clearDataFiles() {
        serviceScope.launch {
            try {
                val dataDir = File(filesDir, DATA_DIR)
                if (dataDir.exists()) {
                    dataDir.listFiles()?.forEach { file ->
                        if (file.extension == "json") {
                            file.delete()
                        }
                    }
                    Log.d(TAG, "Data files cleared")
                }
            } catch (e: Exception) {
                Log.e(TAG, "Error clearing data files", e)
            }
        }
    }

    fun getDataStatistics(): Map<String, Any> {
        val dataDir = File(filesDir, DATA_DIR)
        val dataFiles = dataDir.listFiles { file ->
            file.extension == "json"
        } ?: emptyArray()

        return mapOf(
            "total_files" to dataFiles.size,
            "total_size_bytes" to dataFiles.sumOf { it.length() },
            "last_modified" to if (dataFiles.isNotEmpty()) {
                dateFormat.format(Date(dataFiles.maxOf { it.lastModified() }))
            } else "N/A"
        )
    }
} 